package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.utils.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    @Qualifier("redis")
    private RedisTemplate redisTemplate;


    @PostMapping("/login")
    public Result userLogin(@RequestBody UserInfo userInfo){
        userInfo =  userService.loginCheck(userInfo);
        if(userInfo!=null){
            String token = UUID.randomUUID().toString().replaceAll("-","");
            HashMap map = new HashMap();
            map.put("name",userInfo.getName());
            map.put("nickName",userInfo.getNickName());
            map.put("token",token);
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+token,userInfo.getId().toString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(map);
        }else{
            return Result.fail().message("用户名或密码错误");
        }

    }

    @GetMapping("logout")
    public Result logout(HttpServletRequest request){
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+request.getHeader("token"));
        return Result.ok();
    }

    @GetMapping("/getUserAddress")
    public List<UserAddress> getUserAddressList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);

        List<UserAddress> userAddressList=  userService.getUserAddressList(userId);
        return userAddressList;
    }
}
